package cn.taskservice.redis.idempotent.config;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class ScriptLoader {

    private final Map<String, DefaultRedisScript<Long>> scriptCache = new ConcurrentHashMap<>();

    /**
     * 从 classpath 加载并缓存 Lua 脚本
     * @param path 相对路径，例如 "script/limit.lua"
     * @return RedisScript
     */
    public DefaultRedisScript<Long> loadScript(String path) {
        return scriptCache.computeIfAbsent(path, p -> {
            try (InputStream inputStream = new ClassPathResource(p).getStream()) {
                String lua = IoUtil.readUtf8(inputStream);
                DefaultRedisScript<Long> script = new DefaultRedisScript<>();
                script.setScriptText(lua);
                script.setResultType(Long.class);
                log.info("加载 Lua 脚本成功: {}", path);
                return script;
            } catch (Exception e) {
                log.error("加载 Lua 脚本失败: {}", path, e);
                throw new RuntimeException("读取 Lua 脚本失败: " + path, e);
            }
        });
    }
}